package com.uduemc.jcms.common.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.uduemc.jcms.common.entity.SiteLanguage;
import com.uduemc.jcms.common.service.ISiteLanguageService;
import com.uduemc.jcms.generate.entity.JcmsSite;
import com.uduemc.jcms.generate.entity.JcmsSysLanguage;
import com.uduemc.jcms.generate.service.IJcmsSiteService;
import com.uduemc.jcms.generate.service.IJcmsSysLanguageService;

import cn.hutool.core.collection.CollUtil;

@Service
public class SiteLanguageServiceImpl implements ISiteLanguageService {

	@Autowired
	IJcmsSiteService jcmsSiteServiceImpl;

	@Autowired
	IJcmsSysLanguageService jcmsSysLanguageServiceImpl;

	@Override
	public SiteLanguage defaultSiteLanguage() {
		LambdaQueryWrapper<JcmsSite> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.orderByAsc(JcmsSite::getId).last("LIMIT 1");
		JcmsSite jcmsSite = jcmsSiteServiceImpl.getOne(queryWrapper);
		if (jcmsSite == null) {
			return null;
		}
		return findBySite(jcmsSite);
	}

	@Override
	public SiteLanguage findBySiteId(int siteId) {
		JcmsSite jcmsSite = jcmsSiteServiceImpl.getById(siteId);
		if (jcmsSite == null) {
			return null;
		}
		return findBySite(jcmsSite);
	}

	@Override
	public SiteLanguage findByLanguageId(int languageId) {
		LambdaQueryWrapper<JcmsSite> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(JcmsSite::getLanguageId, languageId).orderByAsc(JcmsSite::getId).last("LIMIT 1");
		JcmsSite jcmsSite = jcmsSiteServiceImpl.getOne(queryWrapper);
		if (jcmsSite == null) {
			return null;
		}
		return findBySite(jcmsSite);
	}

	@Override
	public SiteLanguage findBySite(JcmsSite site) {
		if (site == null) {
			return null;
		}
		SiteLanguage siteLanguage = new SiteLanguage();
		siteLanguage.setSite(site);
		Integer languageId = site.getLanguageId();
		JcmsSysLanguage jcmsSysLanguage = jcmsSysLanguageServiceImpl.getById(languageId);
		if (jcmsSysLanguage != null) {
			siteLanguage.setLanguage(jcmsSysLanguage);
		}
		return siteLanguage;
	}

	@Override
	public SiteLanguage findByLanguage(JcmsSysLanguage language) {
		if (language == null) {
			return null;
		}
		Integer id = language.getId();
		SiteLanguage siteLanguage = findByLanguageId(id);
		return siteLanguage;
	}

	@Override
	public List<SiteLanguage> findAll() {
		LambdaQueryWrapper<JcmsSite> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.orderByAsc(JcmsSite::getId);
		List<JcmsSite> list = jcmsSiteServiceImpl.list(queryWrapper);
		if (CollUtil.isEmpty(list)) {
			return null;
		}
		List<SiteLanguage> siteLanguageList = new ArrayList<>();
		for (JcmsSite site : list) {
			SiteLanguage siteLanguage = findBySite(site);
			siteLanguageList.add(siteLanguage);
		}
		return siteLanguageList;
	}

}
